﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ViewModels;
using ViewModels.MemberVM;
using WebLib;
using WebLib.FileUpload;

namespace HinokyWeb.Controllers
{
    public class IconGeneratorController : Controller
    {
        //
        // GET: /IconGenerator/

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Generate(UploadFileObjVM inputData)
        {
            if (!string.IsNullOrEmpty(inputData.FileName))
            {
                var imageData = inputData.FileData.Split(',');

                if (imageData.Length > 1)
                {
                    var fileName = Path.GetFileNameWithoutExtension(new FileInfo(inputData.FileName).Name);

                    var savedImageBytes = Convert.FromBase64String(imageData[1]);

                    var bitmapObj = ConvertByteArrayToBitmap(savedImageBytes);

                    var newIcon = ImageHelper.ConvertBitmapToIcon(bitmapObj, 32);

                    var result = IconToBytes(newIcon);

                    var path = UploadHelper.UploadIconImage(result, string.Format("{0}.ico", fileName));

                    var resultUrl = string.Format("{0}{1}", "/uploadimage/", path.Replace(@"\", "/"));

                    return
                        Json(new
                        {
                            ResponseImage = result,
                            ResponseFileName = string.Format("{0}.ico", fileName),
                            ResponseFileSize = result.Length,
                            ResponseFileWidth = string.Format("{0}X{1}", newIcon.Size.Width, newIcon.Size.Height),
                            ResponseFileUrl = resultUrl,

                        }, JsonRequestBehavior.AllowGet);
                }
            }

            return Json(new {ResponseImage = ""}, JsonRequestBehavior.AllowGet);
        }

        private byte[] IconToBytes(Icon icon)
        {
            using (var ms = new MemoryStream())
            {
                icon.Save(ms);
                return ms.ToArray();
            }
        }

        private Bitmap ConvertByteArrayToBitmap(byte[] byteArrayIn)
        {
            var ic = new ImageConverter();
            var img = (Image)ic.ConvertFrom(byteArrayIn);

            return img != null ? new Bitmap(img) : null;
        }
    }
}
